<?php

namespace app\admin\controller;

use app\admin\service\CommonService;
use app\admin\service\ContractService;
use app\models\CampusModel;
use app\models\CapitalRecordListModel;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseLogModel;
use app\models\CourseModel;
use app\models\GoodsContractModel;
use app\models\GoodsModel;
use app\models\GradesContractModel;
use app\models\GradesDetailsModel;
use app\models\MemberModel;
use app\models\PackageModel;
use app\models\ReceivablesModel;
use app\models\RefundAmountModel;
use app\models\StudentModel;
use app\models\AllocationCampusModel;
use app\models\AllocationOnlyModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\TeacherModel;
use app\models\UserModel;


class Contract extends Common
{

    /**
     * 物品管理模型.
     *
     *  @var GoodsModel
     */
    protected $goodsModel;


    /**
     * 班级管理详情模型.
     *
     * @var GradesDetailsModel
     */
    protected $gradesdetailModel;

    /**
     * 学生分班排课管理模型.
     *
     * @var StudentSubjectInfosClassModel
     */
    protected $studentsubjectinfosclassModel;

    /**
     * 班级与合同管理模型.
     *
     *  @var GradesContractModel
     */
    protected $gradesContractModel;

    /**
     * 物品与合同管理模型.
     *
     *  @var GoodsContractModel
     */
    protected $goodsContractModel;

    /**
     * 教师管理模型.
     *
     * @var TeacherModel
     */
    protected $teacherModel;

    /**
     * 用户管理模型.
     *
     * @var UserModel
     */
    protected $userModel;

    /**
     * 学员模型.
     *
     * @var StudentModel
     */
    protected $studentModel;

    /**
     * RefundAmountModel 退款订单管理模型.
     *
     * @var RefundAmountModel
     */
    protected $refundamountModel;
	
	/**
     * AllocationCampusModel 校区业绩分配管理模型.
     *
     * @var AllocationCampusModel
     */
    protected $allocationcampusModel;


    /**
     * AllocationOnlyModel 个人业绩分配管理模型.
     *
     * @var AllocationOnlyModel
     */
    protected $allocationonlyModel;
	
    /**
     * CampusModel 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * CapitalRecordListModel 资金回抽分配记录管理模型.
     *
     * @var CapitalRecordListModel
     */
    protected $capitalRecordListModel;

    /**
     * ContractModel 订单管理模型.
     *
     * @var ContractModel
     */
    protected $contractModel;

	/**
	 * 课程订单关系模型.
	 *
	 * @var CourseContractModel
	 */
    protected $courseContractModel;

    /**
     * CourseModel 课程管理模型.
     *
     * @var CourseModel
     */
    protected $courseModel;

    /**
     * ReceivablesModel 收款管理模型.
     *
     * @var ReceivablesModel
     */
    protected $receivablesModel;

    /**
     * CourseLogModel 已报课程管理模型.
     *
     * @var CourseLogModel
     */
    protected $courseLogModel;

    /**
     * 订单管理.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->contractModel->getContractLists($param);
            $this->success('success', '', $campus, 0);
        }
        $where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['id'] = ['in',get_current_campus_id()];
		}

        $campus = $this->campusModel->where($where)->select()->toArray();
        $this->dictionary();

        return $this->fetch('', ['campus' => $campus]);
    }

    /**
     * 修改订单.
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return \think\response\View
     */
    public function edit()
    {
        if (request()->isPost()) {
            return json((new ContractService())->logic($type = 2));
        }

        $contract = $this->contractModel->get(input('cid'));
        $contract['direct_discount'] = $contract['direct_discount'] / 100;
        $contract['total_amount'] = $contract['total_amount'] / 100;
        $contract['preferential'] = $contract['preferential'] / 100;
        $contract['amount'] = $contract['amount'] / 100;
        $contract['stay_amount'] = $contract['stay_amount'] / 100;
        if($contract['input_type'] == 0){
            $contract['input_type_text'] = '新生';
        }else{
            $contract['input_type_text'] = '老生';
        }

        $campus_name = CampusModel::get(['id' => $contract['campus_id']])['campus_name'];

		$student = StudentModel::get(input('sid'));
		$student['channel'] = CommonService::getDictionaryName($student['channel']) ?: '--';
		$student['grade'] = CommonService::getDictionaryName($student['grade']) ?: '--';
		$student['birth'] = $student['birth'] ?: '--';



        $this->assign('id', $contract['id']);
        $this->assign('student', $student);
        $this->assign('contract', $contract);
        $this->assign('campus_name',$campus_name);
        $this->dictionary();


		$campus_where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$campus_where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$campus_where['id'] = ['in',get_current_campus_id()];
		}
		$campus_where['status'] = 1;
        $campus = $this->campusModel->where($campus_where)->select();
        $contract_number = input('contract_number');

        /********签约人************/
        $user_where = [];
        $user_where['status'] = 1;
        if(get_current_type() == 4 || get_current_type() == 5){
            $user_where['campus_id'] = get_current_campus_id();
        }elseif (get_current_type() == 2 || get_current_type() == 3){
            $user_where['campus_id'] = ['in',get_current_campus_id()];
        }
        $user_result = $this->userModel->where($user_where)->select();


        $data_json = [];   //返回前台json
        $total_net_receipts = 0;
        $contract_id = input('cid');
        $res_grades = $this->gradesContractModel->where(['contract_id' => $contract_id])->select();
        foreach ($res_grades as $key => $value) {
            $item = [];
            $result = $this->gradesdetailModel->get(['id' => $value['grades_id']]);
            $course_result = $this->courseModel->get(['id' => $result['course_id']]);
            $item['project_id'] = $value['id'];
            $item['project_info_id'] = $value['grades_id'];
            $item['project_campus_id'] = $value['campus_id'];
            $item['project_name'] = $result['grades_name'].'-'.$course_result['course_name'];
            if($course_result['unit'] == '期'){
                $item['project_price'] = ($course_result['total_price']/100).'/'.$course_result['unit'].'('.$course_result['class_num'].'次课)';
            }else{
                $item['project_price'] = ($course_result['total_price']/100).'/'.$course_result['unit'];
            }
            $item['project_total_price'] =  ($value['total_price']/100);
            $item['project_net_receipts'] = ($value['net_receipts']/100);
            $item['project_num'] = $value['class_num'];
            $item['project_give_class_num'] = $value['give_class_num'];
            $item['project_rate'] = $value['rate'];
            $item['project_assessed_status'] = $value['assessed_status'];
            $item['project_assessed_amount'] = ($value['assessed_amount']/100);
            $item['project_contract_type'] = $value['contract_type'];
            $item['project_direct_money'] = ($value['direct_money']/100);
            $item['project_unit_price'] = ($item['project_total_price'] / $item['project_num']);
            $item['project_type'] = 1; //班级
            if($value['room_seat'] != null && strlen($value['room_seat']) > 0){
                $item['project_seat'] = 1; //设置座位
            }else{
                $item['project_seat'] = 0; //未设置座位
            }
            $data_json[] = $item;
            $total_net_receipts = $total_net_receipts + $item['project_net_receipts'];
        }
        $res_course = $this->courseContractModel->where(['contract_id' => $contract_id])->select();
        foreach ($res_course as $key => $value) {
            $item = [];
            $course_result = $this->courseModel->get(['id' => $value['course_id']]);
            $item['project_id'] = $value['id'];
            $item['project_info_id'] = $value['course_id'];
            $item['project_campus_id'] = $value['campus_id'];
            $item['project_name'] = $course_result['course_name'];
            if($course_result['unit'] == '期'){
                $item['project_price'] = ($course_result['total_price']/100).'/'.$course_result['unit'].'('.$course_result['class_num'].'次课)';
            }else{
                $item['project_price'] = ($course_result['total_price']/100).'/'.$course_result['unit'];
            }
            $item['project_total_price'] =  ($value['total_price']/100);
            $item['project_net_receipts'] = ($value['net_receipts']/100);
            $item['project_num'] = $value['class_num'];
            $item['project_give_class_num'] = $value['give_class_num'];
            $item['project_rate'] = $value['rate'];
            $item['project_assessed_status'] = $value['assessed_status'];
            $item['project_assessed_amount'] = ($value['assessed_amount']/100);
            $item['project_contract_type'] = $value['contract_type'];
            $item['project_direct_money'] = ($value['direct_money']/100);
            $item['project_unit_price'] = ($item['project_total_price'] / $item['project_num']);
            $item['project_type'] = 2; //课程
            $data_json[] = $item;
            $total_net_receipts = $total_net_receipts + $item['project_net_receipts'];
        }
        $res_goods = $this->goodsContractModel->where(['contract_id' => $contract_id])->select();
        foreach ($res_goods as $key => $value) {
            $item = [];
            $goods_result = $this->goodsModel->get(['id' => $value['goods_id']]);
            $item['project_id'] = $value['id'];
            $item['project_info_id'] = $value['goods_id'];
            $item['project_campus_id'] = $value['campus_id'];
            $item['project_name'] = $goods_result['goods_name'];
            if($goods_result['type'] == 0){
                $item['project_price'] = ($goods_result['price']/100).'/'.$goods_result['unit'];
            }else{
                $item['project_price'] = ($goods_result['price']/100).'/'.$goods_result['unit'];
            }
            $item['project_total_price'] =  ($value['total_price']/100);
            $item['project_net_receipts'] = ($value['net_receipts']/100);
            $item['project_num'] = $value['goods_num'];
            $item['project_give_class_num'] = 0;
            $item['project_rate'] = $value['rate'];
            $item['project_assessed_status'] = $value['assessed_status'];
            $item['project_assessed_amount'] = ($value['assessed_amount']/100);
            $item['project_contract_type'] = $value['contract_type'];
            $item['project_direct_money'] = ($value['direct_money']/100);
            $item['project_unit_price'] = ($item['project_total_price'] / $item['project_num']);
            $item['project_type'] = 3; //物品
            $data_json[] = $item;
            $total_net_receipts = $total_net_receipts + $item['project_net_receipts'];
        }
        $json_data = json_encode($data_json);


        return $this->fetch('',['json_data' =>$json_data, 'user' => $user_result,  'campus' => $campus,'contract_number' => $contract_number]);
    }

    /**
     * 收款
     * @throws \think\exception\DbException
     *
     * @return \think\response\Json|\think\response\View
     */
    public function receivables()
    {
        $num = session("item_nums");
        if($num == null){
            $num = 1;
        }

        $num_only = session("item_nums_only");
        if($num_only == null){
            $num_only = 1;
        }

        $assignment = session("assignment");
        $campus_id = session("campus_id");
        $payee = session("payee");
        $payment_method = session("payment_method");
        $amount = session("amount");
        $remark = session("remark");

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');

			$receivables_status = $data['receivables_status']; //来源
            $contract = $this->contractModel->get($data['id']);
            $arr_json_all = $data['arr_json_all'];  //校区业绩分配
            $arr_json_only = $data['arr_json_only'];  //个人业绩分配
            $arr_json_decode_all = json_decode($arr_json_all, true);  //校区业绩
            $arr_json_decode_only = json_decode($arr_json_only, true); //个人业绩
            $arr_json_all = [];
            if (count($arr_json_decode_all) > 0) {    //校区业绩
                for ($i = 0; $i < count($arr_json_decode_all); $i++) {
                    $item = $arr_json_decode_all[$i];
                    $cell_all = [];
                    $cell_all['contract_number'] = $contract['contract_number'];
                    $cell_all['campus_id_all'] = $item['campus_id_all'];
                    $cell_all['campus_id_all_text'] = $item['campus_id_all_text'];
                    $cell_all['assignment_all'] = $item['assignment_all'];
                    $cell_all['assignment_all_text'] = $item['assignment_all_text'];
                    $cell_all['rate_all'] = $item['rate_all'];
					$cell_all['receipt_number'] = $data['receipt_number'];
					$cell_all['operator'] = get_current_id();
                    $cell_all['rate_all_money'] = $item['rate_all_money'] * 100;
                    $cell_all['amount_already_all'] = $item['amount_already_all'] * 100;
                    $arr_json_all[] = $cell_all;
                }
            }
            $arr_json_only = [];
            if (count($arr_json_decode_only) > 0) { //个人业绩
                for ($i = 0; $i < count($arr_json_decode_only); $i++) {
                    $item = $arr_json_decode_only[$i];
                    $cell_only = [];
                    $cell_only['contract_number'] = $contract['contract_number'];
                    $cell_only['payee_only'] = $item['payee_only'];
                    $cell_only['payee_only_text'] = $item['payee_only_text'];
                    $cell_only['assignment_only'] = $item['assignment_only'];
                    $cell_only['assignment_only_text'] = $item['assignment_only_text'];
                    $cell_only['rate_only'] = $item['rate_only'];
                    $cell_only['campus_id'] = $data['campus_id'];  //当前校区ID
					$cell_only['receipt_number'] = $data['receipt_number'];
					$cell_only['operator'] = get_current_id();
                    $cell_only['rate_only_money'] = $item['rate_only_money'] * 100;
                    $cell_only['amount_already_only'] = $item['amount_already_only'] * 100;
                    $arr_json_only[] = $cell_only;
                }
            }
            if(count($arr_json_all) > 0 ){
                    if(!$this->allocationcampusModel->saveAll($arr_json_all)){
                        $this->error('插入校区业绩信息失败', null, '', 1);
                    }
            }
            if(count($arr_json_only) > 0 ){
                if(!$this->allocationonlyModel->saveAll($arr_json_only)){
                    $this->error('插入个人业绩信息失败', null, '', 1);
                }
            }
			$receivables['contract_number'] = $contract['contract_number'];
			$receivables['paydate'] = date('Y-m-d');
			$receivables['payee'] = $data['payee'];
			$receivables['flow_number'] = 'LSH'.date('md').$data['id'];
			$receivables['amount'] = $data['amount'] * 100;
			$receivables['campus_id'] = $data['campus_id'];
			$receivables['receipt_number'] = $data['receipt_number'];
			$receivables['payment_method'] = $data['payment_method'];
			//收款管理写入
			$res = $this->receivablesModel->save($receivables);
            //现金支付
			if($data['payment_method'] == '79'){
				//更新订单状态及金额
				$data['amount'] = $data['amount'] * 100;//已收款金额

				/*********************财务流程**********************/
				//应收【total_amount】  项目收费【amount】  实收【net_receipts】   欠费【stay_amount】    支出【expenditure】   余额【balance】    储值【Storedvalue】
				$total_amount_money = $contract['total_amount']; //应收
				$amount_money = $contract['amount'] +  $data['amount']; //项目收费
				$storedvalue = 0;
				$net_receipts = 0;
				$des_storedvalue = 0;
                $amount_allocation = 0;//分配金额
				if($amount_money <= $total_amount_money){
					$storedvalue = 0;   //储值
					$net_receipts = $amount_money;
                    $amount_allocation = $data['amount'];
				}else if($amount_money > $total_amount_money){
					$des_storedvalue = ($amount_money - $total_amount_money); //储蓄增量
					$storedvalue = ($amount_money - $total_amount_money) + $contract['storedvalue'];
					$amount_money = $total_amount_money;
                    $net_receipts = $amount_money;
                    $amount_allocation = ($total_amount_money -  $contract['amount']);
				}

				$stay_amount_money = ($total_amount_money - $amount_money);  //欠费
				$expenditure_money = $contract['expenditure']; //支出[课消]

				/********************END*****************************/
				{
                    if($amount_allocation > 0){
                        $checked_ids = $data['checked_ids'];//资金分配
                        $checked_ids_arr = explode(',',$checked_ids);

                        //规则：默认先把物品的钱付完
                        for($h = 0; $h < count($checked_ids_arr); $h ++){
                            $pos_value_arr = explode('-',$checked_ids_arr[$h]);
                            if($amount_allocation > 0) {
                                if ($pos_value_arr[1] == 3) {  //物品
                                    $res_good = $this->goodsContractModel->get(['id' => $pos_value_arr[0]]);
                                    $des_good_amount = (($res_good['net_receipts'] - $res_good['assessed_amount']) - $res_good['payment']);
                                    if($amount_allocation >= $des_good_amount){
                                        $amount_allocation = $amount_allocation - $des_good_amount;
                                        $des_good_amount_ = $res_good['payment'] + $des_good_amount;
                                        $payment_balance = $res_good['payment_balance'] + $des_good_amount;
                                        $this->goodsContractModel->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_, 'payment_balance' => $payment_balance]);
                                    }else{
                                        $des_good_amount_ = $res_good['payment'] + $amount_allocation;
                                        $payment_balance = $res_good['payment_balance'] + $amount_allocation;
                                        $this->goodsContractModel->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_,'payment_balance' => $payment_balance]);
                                        $amount_allocation = 0;
                                    }
                                }
                            }
                        }
                        //分课程-分班级-求总应收金额
                        if($amount_allocation > 0) {
                            $net_receipts_amount_total = 0;
                            for ($h = 0; $h < count($checked_ids_arr); $h++) {
                                $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                                if ($pos_value_arr[1] == 1) {  //课程
                                    $res_course = $this->courseContractModel->get(['id' => $pos_value_arr[0]]);
                                    $net_receipts_amount_total = $net_receipts_amount_total + ($res_course['net_receipts'] - $res_course['assessed_amount']);
                                } else if ($pos_value_arr[1] == 2) {   //班级
                                    $res_grades = $this->gradesContractModel->get(['id' => $pos_value_arr[0]]);
                                    $net_receipts_amount_total = $net_receipts_amount_total + ($res_grades['net_receipts'] - $res_grades['assessed_amount']);
                                }

                            }


                            //分配

                            for ($h = 0; $h < count($checked_ids_arr); $h++) {
                                $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                                    if ($pos_value_arr[1] == 1) {  //课程
                                        $res_course = $this->courseContractModel->get(['id' => $pos_value_arr[0]]);
                                        $rate_amount = round(($res_course['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                                        //抵充欠费
                                        $rate_amount_total = $rate_amount;
                                        $contract_number = ContractModel::get(['id' => $res_course['contract_id']])['contract_number'];
                                        $res_info = $this->studentsubjectinfosclassModel->where(['status' => 1, 'report_status' => 1, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_course['course_id']])->select();
                                        foreach ($res_info as $value){
                                            $info_id = $value['id'];
                                            if($rate_amount_total > 0) {
                                                if (($rate_amount_total + $value['arrears_amount']) >= 0) {
                                                    if (!$this->studentsubjectinfosclassModel->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    $rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
                                                } else {
                                                    $value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
                                                    if (!$this->studentsubjectinfosclassModel->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    break;
                                                }
                                            }
                                        }


                                        $rate_amount_ = $res_course['payment'] + $rate_amount;
                                        $payment_balance = $res_course['payment_balance'] + $rate_amount;
                                        $this->courseContractModel->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]);  //更新付款金额


                                        //更新合同应收分配课时
                                        $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                                        $nums = round(($rate_amount / $price_),2);

                                        $course_paid_nums_arr = explode(',',$contract['course_paid_nums']);
                                        $course = explode(',',$contract['course']);
                                        for($l = 0; $l < count($course); $l ++){
                                            if($course[$l] == $res_course['course_id']){
                                                $course_paid_nums_arr[$l] = $course_paid_nums_arr[$l] + $nums;
												$C_Number = $contract['contract_number'];  //合同号
												$Course_Id = $res_course['course_id']; //课程ID
												$Report_Status = 1; //课程
												if($this->studentsubjectinfosclassModel->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){
													
													$this->studentsubjectinfosclassModel->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $course_paid_nums_arr[$l]]);
												}
                                            }
                                        }
                                        $contract['course_paid_nums'] = implode(',',$course_paid_nums_arr);


                                    } else if ($pos_value_arr[1] == 2) {   //班级
                                        $res_grades = $this->gradesContractModel->get(['id' => $pos_value_arr[0]]);
                                        $rate_amount = round(($res_grades['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                                        //抵充欠费
                                        $rate_amount_total = $rate_amount;
                                        $contract_number = ContractModel::get(['id' => $res_grades['contract_id']])['contract_number'];
                                        $res_info = $this->studentsubjectinfosclassModel->where(['status' => 1, 'report_status' => 2, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_grades['course_id']])->select();
                                        foreach ($res_info as $value){
                                            $info_id = $value['id'];
                                            if($rate_amount_total > 0) {
                                                if (($rate_amount_total + $value['arrears_amount']) >= 0) {
                                                    if (!$this->studentsubjectinfosclassModel->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    $rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
                                                } else {
                                                    $value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
                                                    if (!$this->studentsubjectinfosclassModel->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    break;
                                                }
                                            }
                                        }

                                        $rate_amount_ = $res_grades['payment'] + $rate_amount;
                                        $payment_balance = $res_grades['payment_balance'] + $rate_amount;
                                        $this->gradesContractModel->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]); //更新付款金额

                                        //更新合同应收分配课时
                                        $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                                        $nums = round(($rate_amount / $price_),2);

                                        $grades_course_paid_nums_arr = explode(',',$contract['grades_course_paid_nums']);
                                        $grades_course = explode(',',$contract['grades_course']);
                                        for($l = 0; $l < count($grades_course); $l ++){
                                            if($grades_course[$l] == $res_grades['course_id']){
                                                $grades_course_paid_nums_arr[$l] = $grades_course_paid_nums_arr[$l] + $nums;
												$C_Number = $contract['contract_number'];  //合同号
												$Course_Id = $res_grades['course_id']; //课程ID
												$Report_Status = 2; //班级
												if($this->studentsubjectinfosclassModel->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){
													
													$this->studentsubjectinfosclassModel->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $grades_course_paid_nums_arr[$l]]);
												}
													
                                            }
                                        }

                                        $contract['grades_course_paid_nums'] = implode(',',$grades_course_paid_nums_arr);
                                    }

                            }
                        }


                    }

				}
                //学费余额
                $payment_grades_balance = $this->gradesContractModel->where(['contract_id' => $data['id']])->sum('payment_balance');
                $payment_course_balance = $this->courseContractModel->where(['contract_id' => $data['id']])->sum('payment_balance');
                $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和

                $contract_data['course_paid_nums'] = $contract['course_paid_nums'];
                $contract_data['grades_course_paid_nums'] = $contract['grades_course_paid_nums'];
				$contract_data['course_elimination'] = $contract['course_paid_nums'];
                $contract_data['grades_course_elimination'] = $contract['grades_course_paid_nums'];
				$contract_data['stay_amount']  = $stay_amount_money; //欠费
				$contract_data['amount'] = $amount_money;  //报读项目收费
				$contract_data['net_receipts'] = $net_receipts;  //实际收费
				$contract_data['total_amount'] = $total_amount_money;  //应收
				$contract_data['expenditure'] = $expenditure_money;  //课消
				$contract_data['balance'] = $payment_money_balance;  //学费余额(不包含物品费用)
				$contract_data['storedvalue'] = $storedvalue;  //储值

				//更新学生储蓄账户
				$student_result = $this->studentModel->get(['id' => $contract['student_id']]);
				//更新欠费状态
				if($contract_data['balance'] >= 0){
					$this->studentModel->where(['id' => $contract['student_id']])->update(['arrears_status' => 1]);
				}else if($contract_data['balance'] < 0){
					$this->studentModel->where(['id' => $contract['student_id']])->update(['arrears_status' => 0]);
				}
				$srudent_item['storedvalue'] = $student_result['storedvalue'] + $des_storedvalue;
				$this->studentModel->save(['storedvalue' => $srudent_item['storedvalue']],['id' => $contract['student_id']]);

				if($contract_data['stay_amount'] > 0){
					$contract_data['status'] = 3;//订单状态：部分收款订单
				}else{
					$contract_data['status'] = 1;//订单状态：已收款订单
				}
				// 更新已报课程状态
				$this->courseLogModel->save(['status' => $contract_data['status']], ['contract_number' => $contract['contract_number']]);
				// 订单收款流水
				CommonService::writeFlowRecord($contract['contract_number'], 1, $data['amount'], '记录订单收款流水',$data['campus_id'],$receivables['receipt_number'],$data['payment_method']);
				//校区业绩
				$checkCampus = (new AllocationCampusModel())->get(['receipt_number'=>$receivables['receipt_number']]);
				if($checkCampus){
					(new AllocationCampusModel())->where(['receipt_number'=>$receivables['receipt_number']])->update(['status'=>2]);
				}
				//个人业绩
				$checkOnly = (new AllocationOnlyModel())->get(['receipt_number'=>$receivables['receipt_number']]);
				if($checkOnly){
					(new AllocationOnlyModel())->where(['receipt_number'=>$receivables['receipt_number']])->update(['status'=>2]);
				}

				$msg = '收款成功,请等待审核';
				$url = 'Contract/lists';
			}else{
				$msg = '唤起支付中······,请耐心等待';
				$url = '/api/Wxpay/wxsmpay';
			}
			//更新订单支付方式
			$contract_data['pay_type'] = $data['payment_method'];
			$this->contractModel->save($contract_data, ['id' => $data['id']]);
            if (false !== $res) {
                session("item_nums",1);
                session("item_nums_only",1);
                session("assignment",null);
                session("campus_id",null);
                session("payee",null);
                session("payment_method",null);
                session("amount",null);
                session("remark",null);
                //判断是否选定了教务
                $res = $this->studentModel->get(['id' => $contract['student_id']]);
                if($receivables_status == 1){  //来自订单列表
                    if($res){
                        if($res['user_edu_id'] == null || $res['user_edu_id'] == 0){  //未指定教务
                            $this->success($msg, $url, 0, 1);
                        }else{
                            $this->success($msg, $url, $data['checked_ids'], 1);
                        }
                    }
                }else{
                    $this->success($msg, $url, 0, 1);
                }
            }
            $this->error('收款失败', null, '', 1);
        }
		$receivables_status = input('receivables_status'); //来源
        $contract = $this->contractModel->get(input('id'));
        $where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['id'] = ['in',get_current_campus_id()];
		}
        $campus = $this->campusModel->where($where)->select()->toArray();
        $contract['stay_amount'] = $contract['stay_amount'] / 100;
        $contract['balance'] = $contract['balance'] / 100;
        $contract['storedvalue'] = $contract['storedvalue'] / 100;  //储值余额

        //资金分配
        $Project_list = [];
        $res_course_contract = $this->courseContractModel->where(['contract_id' => $contract['id']])->select();
        foreach ($res_course_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                        $course_name =  CourseModel::get(['id' => $value['course_id']])['course_name'];
                        $arrears_amount = ($value['payment'] - ($value['net_receipts'] - $value['assessed_amount'])) / 100;
                        if(($value['net_receipts'] - $value['assessed_amount']) == $value['payment']){
                            $item['project_title'] = $course_name.'(已完缴)';
                        }else{
                            $item['project_title'] = $course_name.'(超缴'.$arrears_amount.'元)';
                        }
                    }else{
                        $course_name =  CourseModel::get(['id' => $value['course_id']])['course_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'] ) / 100;
                        $item['project_title'] = $course_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-1';//课程
                    $item['project_type'] = 1;
                    $Project_list[] = $item;
        }
        $res_grades_contract = $this->gradesContractModel->where(['contract_id' => $contract['id']])->select();
        foreach ($res_grades_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                        $grades_name = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
                        $arrears_amount = ($value['payment'] - ($value['net_receipts'] - $value['assessed_amount'])) / 100;
                        if(($value['net_receipts'] - $value['assessed_amount']) == $value['payment']){
                            $item['project_title'] = $grades_name.'(已完缴)';
                        }else{
                            $item['project_title'] = $grades_name.'(超缴'.$arrears_amount.'元)';
                        }
                    }else{
                        $grades_name = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'])/ 100;
                        $item['project_title'] =$grades_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-2';//班级
                    $item['project_type'] = 2;
                    $Project_list[] = $item;
        }

        $res_goods_contract = $this->goodsContractModel->where(['contract_id' => $contract['id']])->select();
        foreach ($res_goods_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                       continue;
                    }else{
                        $goods_name = GoodsModel::get(['id' => $value['goods_id']])['goods_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'])/ 100;
                        $item['project_title'] =$goods_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-3';//物品
                    $item['project_type'] = 3;
                    $Project_list[] = $item;
        }
        $this->dictionary();
        if($amount == null){
            $amount = $contract['stay_amount'];
        }
        /********收款人************/
        $payee_where = [];
        $payee_where['status'] = 1;
        if(get_current_type() == 4 || get_current_type() == 5){
            $payee_where['campus_id'] = get_current_campus_id();
        }elseif (get_current_type() == 2 || get_current_type() == 3){
            $payee_where['campus_id'] = ['in',get_current_campus_id()];
        }
        $payee_result = $this->userModel->where($payee_where)->select();
        return $this->fetch('', [
            'contract' => $contract,
            'user_id' => get_current_id(),
            'campus' => $campus,
            'time' => 'PZ'.time(),
            'num' => $num,
            'project_list' => $Project_list,
            'num_only' => $num_only,
			'receivables_status' => $receivables_status,

            'assignment' => $assignment,
            'campus_id' => $contract['campus_id'],
            'payee' => $payee,
            'payment_method' => $payment_method,
            'amount' => $amount,
            'remark' => $remark,
            'payee_user' => $payee_result,
        ]);
    }

	/**
	 * 根据不同支付方式执行支付
	 * User: wufeng
	 * Date: 2019/4/11
	 *
	 * @param $payment_method
	 * @return array
	 */
    public function paymentMethod($payment_method)
	{
		$arr = [];

		return $arr;
	}

    /**
     * 资金课时分配【校区列表】.
     *
     * @throws \think\exception\DbException
     *
     * @return \think\response\View
     */
    public function getcampuslist()
    {

        $listdata = $this->campusModel->getContractCampusLists();
        $res_contract = $this->contractModel->get(['contract_number' => input('contract_number')]);
        $campus_name = CampusModel::get(['id' => $res_contract['campus_id']])['campus_name'];
        $this->assign('campus_name', $campus_name);
        $this->assign('campuslist', $listdata);
        $this->assign('res_contract', $res_contract);
        $this->assign('number', input('contract_number'));
        $this->assign('amount', ($res_contract['amount'] / 100));
        $this->assign('stay_distributed', ($res_contract['stay_distributed'] / 100));

        return view('distribution_shown');
    }

    /**
     *  课时分配记录获取.
     */
    public function getdistribution()
    {
        if ($this->request->isAjax()) {
            $contract_number = $_GET['number'];
            $param = $this->request->param();
            $result = $this->contractModel->getContractinfo($param, $contract_number);
            $this->success('success', '', $result, 0);
        }
    }

    /**
     * 资金回抽.
     *
     * @throws \think\exception\DbException
     *
     * @return array|\think\response\View
     */
    public function returnfund()
    {
        if ($this->request->isAjax()) {
            $data = input('post.');
            $money_ = $data['money_'] * 100;  //回抽资金
            $num_ = $data['num_'];  //回抽数量
            $project_id = $_GET['project_id'];  //项目id
            $project_type = $_GET['project_type'];  //项目类型
            $contract_number = $_GET['contract_number'];  //订单编号
            $campus_id = $_GET['campus_id'];  //分配校区

            $nums = 0;
            $course_id_ = 0;
            if($project_type == 1){  //课程
                $res_course = $this->courseContractModel->get(['id' => $project_id]);
                $res_course['payment'] = $res_course['payment'] - $money_;  //到款金额
                $payment_amount = $res_course['payment'];
                //更新合同应收分配课时
                $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                $nums = round(($payment_amount / $price_),2);
                $course_id_ = $res_course['course_id'];
                $res_course['payment_balance'] = $res_course['payment_balance'] - $money_;  //余额
                if(!$this->courseContractModel->where(['id' => $project_id])->update(['payment' => $res_course['payment'], 'payment_balance' => $res_course['payment_balance']])){
                    $this->error('更新课程项目失败', null, '', 1);
                }
            }else if($project_type == 2){  //班级
                $res_grades = $this->gradesContractModel->get(['id' => $project_id]);
                $res_grades['payment'] = $res_grades['payment'] - $money_;  //到款金额
                $payment_amount = $res_grades['payment'];
                $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                $nums = round(($payment_amount / $price_),2);
                $course_id_ = $res_grades['course_id'];
                $res_grades['payment_balance'] = $res_grades['payment_balance'] - $money_;  //余额
                if(!$this->gradesContractModel->where(['id' => $project_id])->update(['payment' => $res_grades['payment'], 'payment_balance' => $res_grades['payment_balance']])){
                    $this->error('更新班级项目失败', null, '', 1);
                }
            }

            $result = $this->contractModel->get(['contract_number' => $contract_number]);
            $stay_distributed = $result['stay_distributed'] + $money_; //待分配金额
            $course_arr = explode(',',$result['course']);  //课程
            $course_paid_nums_arr = explode(',',$result['course_paid_nums']);  //到款数量
            $grades_course_arr = explode(',',$result['grades_course']); //班级
            $grades_course_paid_nums_arr = explode(',',$result['grades_course_paid_nums']);  //到款数量


            //学费余额
            $payment_grades_balance = $this->gradesContractModel->where(['contract_id' => $result['id']])->sum('payment_balance');
            $payment_course_balance = $this->courseContractModel->where(['contract_id' => $result['id']])->sum('payment_balance');
            $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


            if($project_type == 1){ //课程
                $key = array_search($course_id_, $course_arr);
                $course_paid_nums_arr[$key] = $nums;
                $course_paid_str = implode(',',$course_paid_nums_arr);
                $result['amount'] = $result['amount']  - $money_;  //项目总收费
                $result['net_receipts'] = $result['amount'];  //实际收费
                $result['balance'] = $payment_money_balance;  //学费余额
                if(!$this->contractModel->where(['id' => $result['id']])->update(['course_paid_nums' => $course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
                    $this->error('更新合同课程到款项目失败', null, '', 1);
                }
            }else if($project_type == 2){  //班级
                $key = array_search($course_id_, $grades_course_arr);
                $grades_course_paid_nums_arr[$key] = $nums;
                $grades_course_paid_str = implode(',',$grades_course_paid_nums_arr);
                $result['amount'] = $result['amount']  - $money_;  //项目总收费
                $result['net_receipts'] = $result['amount'];  //实际收费
                $result['balance'] = $payment_money_balance;  //学费余额
                if(!$this->contractModel->where(['id' => $result['id']])->update(['grades_course_paid_nums' => $grades_course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
                    $this->error('更新合同班级到款项目失败', null, '', 1);
                }
            }

            $capital_allocation_id = time();
            //插入资金回抽记录
            $data = [
                'campus_id' => $campus_id,  //签约校区
                'contractor' => $result['contractor'],  //签约人
                'student_name' => $result['student_name'],  //学员姓名
                'contract_number' => $contract_number,
                'capital_allocation_id' => $capital_allocation_id,
                'distributive_person' => get_current_id(),  //获取当前登录用户ID
                'project_id' => $project_id,  //项目ID
                'project_type' => $project_type,  //项目类型
                'allocation_fund' => -$money_,
                'allotted_quantity' => $num_,
            ];
            $this->capitalRecordListModel->create($data);  //插入记录

            return ['code' => 1, 'msg' => '资金回抽成功'];
        }
        $project_id = $_GET['project_id'];
        $project_type= $_GET['project_type'];
        $contract_number = $_GET['contract_number'];
        $price = 0;
        if($project_type == 1){  //课程
            $course_res = $this->courseContractModel->get(['id' => $project_id]);
            $price = round(((($course_res['net_receipts'] - $course_res['assessed_amount'])/($course_res['class_num']))/100),2);
        }else if($project_type == 2){  //班级
            $grades_res = $this->gradesContractModel->get(['id' => $project_id]);
            $price = round(((($grades_res['net_receipts'] - $grades_res['assessed_amount'])/($grades_res['class_num']))/100),2);
        }

        $campus_id = $_GET['campus_id'];  //分配校区
        $this->assign('campus_id', $campus_id);
        $this->assign('unit_price', $price);
        $this->assign('project_surplus_amount', $_GET['project_surplus_amount']);
        $this->assign('project_id', $project_id);
        $this->assign('project_type', $project_type);
        $this->assign('contract_number', $contract_number);

        return view();
    }

    /**
     *  资金分配.
     *
     * @throws \think\exception\DbException
     *
     * @return array|\think\response\View
     */
    public function allocationfund()
    {
        if ($this->request->isAjax()) {
            $data = input('post.');
            $money_ = $data['money_'] * 100;  //分配资金
            $num_ = $data['num_'];  //分配数量
            $project_id = $_GET['project_id'];  //项目id
            $project_type = $_GET['project_type'];  //项目类型
            $contract_number = $_GET['contract_number'];  //订单编号
            $campus_id = $_GET['campus_id'];  //分配校区

            $nums = 0;
            $course_id_ = 0;
            if($project_type == 1){  //课程
                $res_course = $this->courseContractModel->get(['id' => $project_id]);
                $res_course['payment'] = $res_course['payment'] + $money_;  //到款金额
                $payment_amount = $res_course['payment'];
                //更新合同应收分配课时
                $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                $nums = round(($payment_amount / $price_),2);
                $course_id_ = $res_course['course_id'];
                $res_course['payment_balance'] = $res_course['payment_balance'] + $money_;  //余额
                if(!$this->courseContractModel->where(['id' => $project_id])->update(['payment' => $res_course['payment'], 'payment_balance' => $res_course['payment_balance']])){
                    $this->error('更新课程项目失败', null, '', 1);
                }
            }else if($project_type == 2){  //班级
                $res_grades = $this->gradesContractModel->get(['id' => $project_id]);
                $res_grades['payment'] = $res_grades['payment'] + $money_;  //到款金额
                $payment_amount = $res_grades['payment'];
                $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                $nums = round(($payment_amount / $price_),2);
                $course_id_ = $res_grades['course_id'];
                $res_grades['payment_balance'] = $res_grades['payment_balance'] + $money_;  //余额
                if(!$this->gradesContractModel->where(['id' => $project_id])->update(['payment' => $res_grades['payment'], 'payment_balance' => $res_grades['payment_balance']])){
                    $this->error('更新班级项目失败', null, '', 1);
                }
            }

            $result = $this->contractModel->get(['contract_number' => $contract_number]);
            $stay_distributed = $result['stay_distributed'] - $money_; //待分配金额
            $course_arr = explode(',',$result['course']);  //课程
            $course_paid_nums_arr = explode(',',$result['course_paid_nums']);  //到款数量
            $grades_course_arr = explode(',',$result['grades_course']); //班级
            $grades_course_paid_nums_arr = explode(',',$result['grades_course_paid_nums']);  //到款数量


            //学费余额
            $payment_grades_balance = $this->gradesContractModel->where(['contract_id' => $result['id']])->sum('payment_balance');
            $payment_course_balance = $this->courseContractModel->where(['contract_id' => $result['id']])->sum('payment_balance');
            $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


            if($project_type == 1){ //课程
                $key = array_search($course_id_, $course_arr);
                $course_paid_nums_arr[$key] = $nums;
                $course_paid_str = implode(',',$course_paid_nums_arr);
                $result['amount'] = $result['amount']  + $money_;  //项目总收费
                $result['net_receipts'] = $result['amount'];  //实际收费
                $result['balance'] = $payment_money_balance;  //学费余额
                if(!$this->contractModel->where(['id' => $result['id']])->update(['course_paid_nums' => $course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
                    $this->error('更新合同课程到款项目失败', null, '', 1);
                }
            }else if($project_type == 2){  //班级
                $key = array_search($course_id_, $grades_course_arr);
                $grades_course_paid_nums_arr[$key] = $nums;
                $grades_course_paid_str = implode(',',$grades_course_paid_nums_arr);
                $result['amount'] = $result['amount']  + $money_;  //项目总收费
                $result['net_receipts'] = $result['amount'];  //实际收费
                $result['balance'] = $payment_money_balance;  //学费余额
                if(!$this->contractModel->where(['id' => $result['id']])->update(['grades_course_paid_nums' => $grades_course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
                    $this->error('更新合同班级到款项目失败', null, '', 1);
                }
            }
            $capital_allocation_id = time();
            //插入资金分配记录
            $data = [
                'campus_id' => $campus_id,  //签约校区
                'contractor' => $result['contractor'],  //签约人
                'student_name' => $result['student_name'],  //学员姓名
                'contract_number' => $contract_number,
                'capital_allocation_id' => $capital_allocation_id,
                'distributive_person' => get_current_id(),  //获取当前登录用户ID
                'project_id' => $project_id,  //项目ID
                'project_type' => $project_type,  //项目类型
                'allocation_fund' => $money_,
                'allotted_quantity' => $num_,
            ];
            $this->capitalRecordListModel->create($data);  //插入记录

            return ['code' => 1, 'msg' => '资金分配成功'];
        }

        $project_id = $_GET['project_id'];
        $project_type= $_GET['project_type'];
        $contract_number = $_GET['contract_number'];  //订单编号
        $campus_id = $_GET['campus_id'];  //分配校区
        $amount = $_GET['amount'];  //已收款金额
        $stay_distributed = $_GET['stay_distributed'];  //待分配金额
        $price = 0;
        if($project_type == 1){  //课程
            $course_res = $this->courseContractModel->get(['id' => $project_id]);
            $price = round(((($course_res['net_receipts'] - $course_res['assessed_amount'])/($course_res['class_num']))/100),2);
        }else if($project_type == 2){  //班级
            $grades_res = $this->gradesContractModel->get(['id' => $project_id]);
            $price = round(((($grades_res['net_receipts'] - $grades_res['assessed_amount'])/($grades_res['class_num']))/100),2);
        }

        $this->assign('campus_id', $campus_id);
        $this->assign('project_id', $project_id);
        $this->assign('project_type', $project_type);
        $this->assign('unit_price', $price);
        $this->assign('amount', $amount);
        $this->assign('project_stay_distributed', $stay_distributed);
        $this->assign('contract_number', $contract_number);

        return view();
    }

    /**
     * 资金分配记录.
     *
     * @throws \think\exception\DbException
     */
    public function capitalrecord()
    {
        if ($this->request->isAjax()) {
            $contract_number = $_GET['number'];
            $param = $this->request->param();
            $result = $this->capitalRecordListModel->getCapitalRecordListLists($param, $contract_number);
            $this->success('success', '', $result, 0);
        }
    }

	    /***业绩分配**/

    public function performance(){
        $contract = '';
        if(isset($_GET["id"])){
            $contract = $this->contractModel->get(['id' => $_GET["id"]]);
            $contract['collection_date'] = $this->receivablesModel->get(['contract_number' => $contract['contract_number']])[''];
        }

        return $this->fetch('',['contract' => $contract]);
    }

    public function additem(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $assignment = $data['assignment'];
            $campus_id = $data['campus_id'];
            $payee = $data['payee'];
            $payment_method = $data['payment_method'];
            $amount = $data['amount'];
            $remark = $data['remark'];


            session("assignment",$assignment);
            session("campus_id",$campus_id);
            session("payee",$payee);
            session("payment_method",$payment_method);
            session("amount",$amount);
            session("remark",$remark);

            $num = session("item_nums");
            if($num == null){
                $num = 1;
            }
            session("item_nums",$num+1);  //增加的数量

            $this->success('', '', '', 0);
        }

    }

    public function deleteitem(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $assignment = $data['assignment'];
            $campus_id = $data['campus_id'];
            $payee = $data['payee'];
            $payment_method = $data['payment_method'];
            $amount = $data['amount'];
            $remark = $data['remark'];


            session("assignment",$assignment);
            session("campus_id",$campus_id);
            session("payee",$payee);
            session("payment_method",$payment_method);
            session("amount",$amount);
            session("remark",$remark);

            $num = session("item_nums");
            if($num > 1){
                session("item_nums",$num-1);
            }
              //减少的数量
            $this->success('', '', '', 0);
        }

    }

    public function additemonly(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $assignment = $data['assignment'];
            $campus_id = $data['campus_id'];
            $payee = $data['payee'];
            $payment_method = $data['payment_method'];
            $amount = $data['amount'];
            $remark = $data['remark'];


            session("assignment",$assignment);
            session("campus_id",$campus_id);
            session("payee",$payee);
            session("payment_method",$payment_method);
            session("amount",$amount);
            session("remark",$remark);

            $num_only = session("item_nums_only");
            if($num_only == null){
                $num_only = 1;
            }
            session("item_nums_only",$num_only+1);  //增加的数量
            $this->success('', '', '', 0);
        }

    }

    public function deleteitemonly(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $assignment = $data['assignment'];
            $campus_id = $data['campus_id'];
            $payee = $data['payee'];
            $payment_method = $data['payment_method'];
            $amount = $data['amount'];
            $remark = $data['remark'];


            session("assignment",$assignment);
            session("campus_id",$campus_id);
            session("payee",$payee);
            session("payment_method",$payment_method);
            session("amount",$amount);
            session("remark",$remark);

            $num_only = session("item_nums_only");
            if($num_only > 1){
                session("item_nums_only",$num_only-1);
            }
            //减少的数量
            $this->success('', '', '', 0);
        }

    }

    //右上角关闭按钮
    public function close(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            session("item_nums",1);
            session("item_nums_only",1);
            session("assignment",null);
            session("campus_id",null);
            session("payee",null);
            session("payment_method",null);
            session("amount",null);
            session("remark",null);

            $this->success('', '', '', 0);
        }
    }



    //退款
    public function refund(){
        $contract = '';
        $signing_type = 0;
        if(isset($_GET['id'])){
            $contract = $this->contractModel->get(['id' => $_GET['id']]);
            $contract['total_amount'] = $contract['total_amount'] / 100;
            $contract['amount'] = $contract['amount'] / 100;
            $contract['balance'] = $contract['balance'] / 100;
            $contract['account_balance'] = (StudentModel::get(['id' => $contract['student_id']])['storedvalue']) / 100;  //该学生账户余额
            $contract['receipt_number'] = 'TK'.date("Ymd").time();
            if($contract['signing_type'] == 114){  //储值新签
                $signing_type = 1;
            }else if($contract['signing_type'] == 75){  //常规新签
                $signing_type = 0;
            }

        }
        $this->dictionary();

        return $this->fetch('',['contract' => $contract,'type' => $signing_type]);
    }

    //退款学费
    public function refund_tuition(){
        $contract = '';
        $Project_list = [];
        if(isset($_GET['id'])){
            $contract = $this->contractModel->get(['id' => $_GET['id']]);
            $contract['total_amount'] = $contract['total_amount'] / 100;
            $contract['amount'] = $contract['amount'] / 100;
            $contract['balance'] = $contract['balance'] / 100;
            $contract['account_balance'] = (StudentModel::get(['id' => $contract['student_id']])['storedvalue']) / 100;  //该学生账户余额
            $contract['receipt_number'] = 'TK'.date("Ymd").time();

            $payment_balance = $this->goodsContractModel->where(['contract_id' => $contract['id']])->sum('payment_balance');
            $contract['goods_payment_balance'] = $payment_balance / 100;

            //资金分配
            $res_course_contract = $this->courseContractModel->where(['contract_id' => $contract['id']])->select();
            foreach ($res_course_contract as $value){
                if($value['payment_balance'] > 0) {
                    $item = [];
                    $item['project_title'] = CourseModel::get(['id' => $value['course_id']])['course_name'];
                    $item['project_id'] = $value['id'];//课程
                    $item['project_type'] = 1;//课程
                    $item['project_payment_balance'] = $value['payment_balance'] / 100;
                    $Project_list[] = $item;
                }
            }
            $res_grades_contract = $this->gradesContractModel->where(['contract_id' => $contract['id']])->select();
            foreach ($res_grades_contract as $value){
                if($value['payment_balance'] > 0) {
                    $item = [];
                    $item['project_title'] = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
                    $item['project_id'] = $value['id'];
                    $item['project_type'] = 2;//班级
                    $item['project_payment_balance'] = $value['payment_balance'] / 100;
                    $Project_list[] = $item;
                }
            }

            $res_goods_contract = $this->goodsContractModel->where(['contract_id' => $contract['id']])->select();
            foreach ($res_goods_contract as $value){
                if($value['payment_balance'] > 0) {
                    $item = [];
                    $item['project_title'] = GoodsModel::get(['id' => $value['goods_id']])['goods_name'];
                    $item['project_id'] = $value['id'];
                    $item['project_type'] = 3;//物品
                    $item['project_payment_balance'] = $value['payment_balance'] / 100;
                    $Project_list[] = $item;
                }
            }

            if($contract['account_balance'] > 0) {
                $item = [];
                $item['project_title'] = '储值账户';
                $item['project_id'] = $contract['student_id'];
                $item['project_type'] = 4;//储值
                $item['project_payment_balance'] = $contract['account_balance'];
                $Project_list[] = $item;
            }

        }
        $this->dictionary();
        $Project_list = json_encode($Project_list);
        return $this->fetch('',['Project_list' => $Project_list, 'contract' => $contract]);
    }

    public function saverefund(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if(input('type_status') == 2){  //订单退费
                $contract_id = $data['contract_id']; //合同ID
                $data_ = $this->contractModel->get(['id' => $contract_id]);
                $data_refund['contract_number'] = $data_['contract_number']; //合同号
                $data_refund['student_name'] = $data_['student_name']; //姓名
                $data_refund['total_amount'] = $data_['total_amount']; //总额
                $data_refund['amount'] = $data_['amount']; //已收
                $data_refund['experienced_person'] = get_current_id(); //操作人
                $data_refund['refund_channel'] = $data['refund_channel']; //退款通道
                $data_refund['receipt_number'] = $data['receipt_number']; //退款凭证
                $data_refund['campus_id'] = $data_['campus_id']; //退款校区
                $data_refund['campus_name'] = CampusModel::get(['id' => $data_['campus_id']])['campus_name']; //退款校区名称

                $json = json_decode($data['json'], true);
                $refund_amount = 0; //退款金额
                $amount_project = 0; //项目金额
                for ($i = 0; $i < count($json); $i++) {
                    $item = $json[$i];
                    $id = $item['id'];  //id
                    $type = $item['type']; //类型 1:课程  2:班级  3:物品  4:账户
                    $amount = $item['amount']*100; //金额
                    $refund_amount= $refund_amount +  $amount; //退款金额

                    if($type == 1){
                        $amount_project = $amount_project + $amount;
                        $res_course = $this->courseContractModel->get(['id' => $id]);
                        $payment_balance = ($res_course['payment_balance'] - $amount);
                        $payment = ($res_course['payment'] - $amount);
                        $this->courseContractModel->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);


                        //更新合同应收分配课时
                        $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                        $nums = round(($payment / $price_),2);

                        $course_arr = explode(',',$data_['course']);
                        $key = array_search($res_course['course_id'], $course_arr);
                        $course_paid_nums_arr = explode(',',$data_['course_paid_nums']);
                        $course_paid_nums_arr[$key] = $nums;
                        $course_paid_nums = implode(',',$course_paid_nums_arr);

                        $this->contractModel->where(['id' => $contract_id])->update(['course_paid_nums' => $course_paid_nums]);


                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单课程退款流水', $data_['campus_id'], $data['receipt_number'], $data['refund_channel']);
                    }else if($type == 2){
                        $amount_project = $amount_project + $amount;
                        $res_grades = $this->gradesContractModel->get(['id' => $id]);
                        $payment_balance = ($res_grades['payment_balance'] - $amount);
                        $payment = ($res_grades['payment'] - $amount);
                        $this->gradesContractModel->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);

                        $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                        $nums = round(($payment / $price_),2);

                        $grades_arr = explode(',',$data_['grades_course']);
                        $key = array_search($res_grades['course_id'], $grades_arr);
                        $grades_course_paid_nums_arr = explode(',',$data_['grades_course_paid_nums']);
                        $grades_course_paid_nums_arr[$key] = $nums;
                        $grades_course_paid_nums = implode(',',$grades_course_paid_nums_arr);

                        $this->contractModel->where(['id' => $contract_id])->update(['grades_course_paid_nums' => $grades_course_paid_nums]);


                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单班级退款流水', $data_['campus_id'], $data['receipt_number'], $data['refund_channel']);
                    }else if($type == 3){
                        $amount_project = $amount_project + $amount;
                        $res_goods = $this->goodsContractModel->get(['id' => $id]);
                        $payment_balance = ($res_goods['payment_balance'] - $amount);
                        $payment = ($res_goods['payment'] - $amount);
                        $this->goodsContractModel->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);
                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单物品退款流水', $data_['campus_id'], $data['receipt_number'], $data['refund_channel']);
                    }else if($type == 4){
                        $res_student = $this->studentModel->get(['id' => $id]);
                        $storedvalue = ($res_student['storedvalue'] - $amount);
                        $this->studentModel->where(['id' => $id])->update(['storedvalue' => $storedvalue]);

                        $res_contract = $this->contractModel->get(['id' => $contract_id]);
                        $contract_storedvalue = ($res_contract['storedvalue'] - $amount);
                        $this->contractModel->where(['id' => $contract_id])->update(['storedvalue' => $contract_storedvalue]);

                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单储值退款流水', $data_['campus_id'], $data['receipt_number'], $data['refund_channel']);
                    }

                }

                //学费余额
                $payment_grades_balance = $this->gradesContractModel->where(['contract_id' => $contract_id])->sum('payment_balance');
                $payment_course_balance = $this->courseContractModel->where(['contract_id' => $contract_id])->sum('payment_balance');
                $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


                //项目总收
                $data_['amount'] = $data_['amount'] - $amount_project;
                //实收
                $data_['net_receipts'] = $data_['net_receipts'] - $amount_project;
                //欠费
                $data_['stay_amount'] = $data_['total_amount'] - $data_['amount'];

                $this->contractModel->where(['id' => $contract_id])->update(['balance' => $payment_money_balance, 'amount' => $data_['amount'], 'net_receipts' => $data_['net_receipts'], 'stay_amount' => $data_['stay_amount']]);

              //  $data_refund['balance'] = $data_['balance']; //余额
				$data_refund['balance'] = $payment_money_balance; //余额
                $data_refund['refund_amount'] = $refund_amount;

                if (!$this->refundamountModel->save($data_refund)) {
                    $this->error('退款失败', null, '', 1);
                }

                $this->success('退款成功,退款订单生成', '', '', 0);
            }else {   //储值退费
                //化成分
                $data['amount'] = $data['amount'] * 100;
                $data['total_amount'] = $data['total_amount'] * 100;
                $data['balance'] = ($data['balance'] - $data['refund_amount']) * 100;
                $data['refund_amount'] = $data['refund_amount'] * 100;
                $result_campus = $this->contractModel->get(['contract_number' => $data['contract_number']]);
                $data['campus_id'] = $result_campus['campus_id'];  //校区ID
                $data['campus_name'] = $this->campusModel->get(['id' => $result_campus['campus_id']])['campus_name']; //校区名字
                if (!$this->refundamountModel->save($data)) {
                    $this->error('退款失败', null, '', 1);
                }
                $updateData = [];
                if (input('type') == 0) {
                    $updateData = array(
                        'balance' => $data['balance'],//余额更新
                        'net_receipts' => $result_campus['net_receipts'] - $data['amount'],//实际收款更新
                        'amount' => $result_campus['amount'] - $data['amount'],//课程收费更新
                        'stay_amount' => $result_campus['stay_amount'] + $data['amount'],//欠费更新
                    );
                } else if (input('type') == 1) {
                    $updateData = array(
                        'storedvalue' => $data['balance'],//储值
                    );
                }
                if (input('type') == 0) {
                    if (!$this->contractModel->where(['contract_number' => $data['contract_number']])->update($updateData)) {
                        $this->error('更新订单账户余额失败', null, '', 1);
                    }
                }
                if (input('type') == 1) {
                    $storedvalue = $this->studentModel->get(['id' => $result_campus['student_id']])['storedvalue'];
                    $storedvalue = $storedvalue - $data['refund_amount'];
                    if (!$this->studentModel->where(['id' => $result_campus['student_id']])->update(['storedvalue' => $storedvalue])) {
                        $this->error('更新个人账户储蓄余额失败', null, '', 1);
                    }
                }

                //退费流水
                CommonService::writeFlowRecord($data['contract_number'], 2, $data['refund_amount'], '记录订单储值退款流水', $data['campus_id'], $data['receipt_number'], $data['refund_channel']);

                $this->success('退款成功,退款订单生成', '', '', 0);
            }
        }

    }



	/**
	 * 新增课程订单关系
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function course_contract()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			if ('1' == input('type')) {
				$data = input('post.');
				$data['total_price'] = $data['price'] * 100 * $data['class_num'];
				$data['price'] = $data['price'] * 100;
				$data['campus_id'] = get_current_campus_id();
				unset($data['type']);
				$res = $this->courseContractModel->save($data, ['id' => $data['id']]);
				$contract_id = $this->courseContractModel->contract_id;
				$courseContracts = $this->courseContractModel->where(['contract_id' => $contract_id])->select();
				$total_price = 0;
				foreach ($courseContracts as &$contract) {
					$total_price += $contract['price'] * $contract['class_num'] / 100;
				}
				$arr['total_price'] = $total_price;
				$arr['contract_id'] = $contract_id;
				if (false !== $res) {
					$this->success('更新成功', '', $arr, 1);
				}
				$this->error('更新失败', null, '', 1);
			} else {
				$data['course_id'] = input('course');
				$cid = input('cid');
				if(input('student_id')){
					$data['student_id'] = input('student_id');
				}
				if (!$cid) {
					$this->contractModel->save(['contract_number' => CommonService::generateNumber()]);
					$id = $this->contractModel->id;
				} else {
					$id = $cid;
				}
				$course = $this->courseModel->get(['id' => $data['course_id']]);
				$data['contract_id'] = $id;
				$data['campus_id'] = get_current_campus_id();;
				$data['price'] = $course['price'];
				$data['total_price'] = $course['total_price'];
				$data['class_num'] = $course['class_num'];
				$this->courseContractModel->save($data);
				$arr['total_price'] = $this->courseContractModel->where(['contract_id' => $id])->sum('total_price') / 100;
				$arr['contract_id'] = $id;
				$this->success('success', '', $arr, 0);
			}
		}
		if (input('campus_id')) {
			$where['campus_id'] = input('campus_id');
		} else {
			$where['campus_id'] = get_current_campus_id();
		}
		$campus_name = CampusModel::getById($where['campus_id'], 'campus_name');
		$where['status'] = 1;
		$students = $this->studentModel->where($where)->order('update_time desc')->select();
		$course = $this->courseModel->where($where)->order('update_time desc')->select();
		foreach ($course as $value) {
			$value['student_grade'] = CommonService::getDictionaryName($value['student_grade']);
			$value['subject'] = CommonService::getDictionaryName($value['subject']);
			$value['price'] = $value['price'] / 100;
			$value['total_price'] = $value['total_price'] / 100;
		}
		foreach ($students as $student) {
			$student['grade'] = CommonService::getDictionaryName($student['grade']);
		}
		$this->dictionary();
		$res = $type = '';
		if(input('student_id')){
			$res = $this->studentModel->get(input('student_id'));
			if($res['is_audition'] < 2){
				$this->studentModel->save(['is_audition'=>2],['id'=>input('student_id')]);
			}
			$grade = DictionaryModel::getById($res['grade'],'name');
			$channel = DictionaryModel::getById($res['channel'],'name');
			$res['grade'] = $grade ? $grade : '--';
			$res['channel'] = $channel ? $channel : '--';
			$res['birth'] = $res['birth'] ? $res['birth'] : '--';
			$type = input('type') ? input('type') : 1;
		}else{
			$type = input('type');
		}

		return $this->fetch('', [
			'student_info' => $res,
			'type' => $type,
			'student' => $students,
			'course' => $course,
			'campus_name' => $campus_name,
			'campus_id' => input('campus_id'),
			'student_id' => input('student_id'),
			'contractor' => get_current_name(),
			'date' => date('Y-m-d'),
		]);
	}

	/**
	 * 删除课程订单关系.
	 */
	public function course_contract_del()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			if (false !== $this->courseContractModel->where(['id' => input('id')])->delete()) {
				$id = input('contract_id');
				$arr['total_price'] = $this->courseContractModel->where(['contract_id' => $id])->sum('total_price') / 100;
				$arr['contract_id'] = $id;
				$this->success('删除成功', url('Campus/lists'), $arr, 1);
			}
			$this->error('删除失败', null, '', 1);
		}
	}

    /**
     * 课程订单关系.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return \think\response\Json|\think\response\View
     */
    public function course_contract_lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['status_infos'] = input('status_infos');
            $param['campus_id'] = input('campus_id');
            $course = $this->courseContractModel->getCourseContractLists($param);

            $this->success('success', '', $course, 0);
        }
        $students = $this->studentModel->where(['status' => 1])->select();
        $course = $this->courseModel->where(['status' => 1])->select();
        foreach ($course as $value) {
            $value['student_grade'] = CommonService::getDictionaryName($value['student_grade']);
            $value['subject'] = CommonService::getDictionaryName($value['subject']);
            $value['price'] = $value['price'] / 100;
            $value['total_price'] = $value['total_price'] / 100;
        }
        foreach ($students as $student) {
            $student['grade'] = CommonService::getDictionaryName($student['grade']);
        }
        $this->dictionary();

        return $this->fetch('', [
            'student' => $students,
            'course' => $course,
        ]);
    }


    /**
     * 修改订单删除课程订单关系.
     */
    public function edit_course_contract_del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            if (false !== $this->courseContractModel->where(['id' => input('id')])->update(['status' => -1])) {
                $id = input('contract_id');
                $arr['total_price'] = $this->courseContractModel->where(['contract_id' => $id,'status' => array('neq',-1)])->sum('total_price') / 100;
                $arr['contract_id'] = $id;
                $this->success('删除成功', url('Campus/lists'), $arr, 1);
            }
            $this->error('删除失败', null, '', 1);
        }
    }



    /**
     * 编辑订单新增课程订单关系
     * modify by Small Y
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_course_contract()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            if ('1' == input('type')) {
                $data = input('post.');
                $data['total_price'] = $data['price'] * 100 * $data['class_num'];
                $data['price'] = $data['price'] * 100;
                unset($data['type']);
                $res = $this->courseContractModel->save($data, ['id' => $data['id']]);
                $contract_id = $this->courseContractModel->contract_id;
                $courseContracts = $this->courseContractModel->where(['contract_id' => $contract_id])->select();
                $total_price = 0;
                foreach ($courseContracts as &$contract) {
                    $total_price += $contract['price'] * $contract['class_num'] / 100;
                }
                $arr['total_price'] = $total_price;
                $arr['contract_id'] = $contract_id;
                if (false !== $res) {
                    $this->success('更新成功', '', $arr, 1);
                }
                $this->error('更新失败', null, '', 1);
            } else {
                $data['course_id'] = input('course');
                $cid = input('cid');
                if(input('student_id')){
                    $data['student_id'] = input('student_id');
                }
                if (!$cid) {
                    $this->contractModel->save(['contract_number' => CommonService::generateNumber()]);
                    $id = $this->contractModel->id;
                } else {
                    $id = $cid;
                }
                $course = $this->courseModel->get(['id' => $data['course_id']]);
                $data['contract_id'] = $id;
                $data['campus_id'] = input('campus_id');
                $data['price'] = $course['price'];
                $data['total_price'] = $course['total_price'];
                $data['class_num'] = $course['class_num'];
                $data['status'] = 2; //增加课程
                $this->courseContractModel->save($data);
                $arr['total_price'] = $this->courseContractModel->where(['contract_id' => $id, 'status' => array('neq',-1)])->sum('total_price') / 100;
                $arr['contract_id'] = $id;
                $this->success('success', '', $arr, 0);
            }
        }

    }


    /**
     * 返回
     * modify by Small Y
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_backcontract_lists(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $cid = input('cid');
            $campus_id = input('campus_id');

            $this->courseContractModel->where(['contract_id' => $cid, 'campus_id' => $campus_id, 'status' => -1])->update(['status' => 1]);
            $this->courseContractModel->where(['contract_id' => $cid, 'campus_id' => $campus_id, 'status' => 2])->delete();

            $this->success('', '', '', 0);

        }

    }


    /******选择教务-学管师****/
    public function eduadmin(){
        $campus_where = [];
        $campus_where['id'] = input('campus_id');  //校区ID
        $contract_id = input('contract_id'); //合同ID
        $campus_where['status'] = 1;
        $campus = $this->campusModel->where($campus_where)->select();
        $this->dictionary();
        return $this->fetch('',[
            'campus'=>$campus,
            'campus_id' => input('campus_id'),
            'contract_id' => $contract_id,
        ]);
    }

    /**********提交*************/
    public function wxsubmit_update_status(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $cid = input('cid');
            $campus_id = input('campus_id');

            $this->courseContractModel->where(['contract_id' => $cid, 'campus_id' => $campus_id, 'status' => -1])->delete();
            $this->courseContractModel->where(['contract_id' => $cid, 'campus_id' => $campus_id, 'status' => 2])->update(['status' => 1]);

            $this->success('', '', '', 0);

        }
    }

    /**************选择教务老师****************/
    public function choice_edu_user(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $user_edu_id = input('user_edu_id');  //教务ID
            $user_edu_name = input('user_edu_name');  //教务名字
            $contract_id = input('contract_id'); //合同ID
            $res_contract = $this->contractModel->get(['id' => $contract_id]);
            $student_id = $res_contract['student_id'];  //学生ID

            $res_edu_result = $this->studentModel->get(['id' => $student_id]);
            if($res_edu_result['user_edu_id'] != null && $res_edu_result['user_edu_id'] != 0){
                $arr = explode(',',$res_edu_result['user_edu_id']);
                if(in_array($user_edu_id,$arr)){
                    $this->success('选择教务/学管('.$user_edu_name.')师成功', '', '', 1);
                }else{
                    $user_edu_id = $res_edu_result['user_edu_id'].','.$user_edu_id;
                    $user_edu_id_arr = explode(',',$user_edu_id);
                    $user_edu_id_arr = array_unique($user_edu_id_arr);
                    $user_edu_id = implode(',',$user_edu_id_arr);
                    $res = $this->studentModel->where(['id' => $student_id])->update(['user_edu_id' => $user_edu_id]);
                    if(!$res){
                        $this->error('选择教务/学管师失败', null, '', 1);
                    }
                }

            }else{
                $res = $this->studentModel->where(['id' => $student_id])->update(['user_edu_id' => $user_edu_id]);
                if(!$res){
                    $this->error('选择教务/学管师失败', null, '', 1);
                }
            }
            $this->success('选择教务/学管('.$user_edu_name.')师成功', '', '', 1);

        }
    }

    /**
     * 实例化.
     *
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->campusModel = new CampusModel();
        $this->contractModel = new ContractModel();
        $this->receivablesModel = new ReceivablesModel();
        $this->courseModel = new CourseModel();
        $this->courseLogModel = new CourseLogModel();
        $this->courseContractModel = new CourseContractModel();
        $this->capitalRecordListModel = new CapitalRecordListModel();
		$this->allocationcampusModel = new AllocationCampusModel();
        $this->allocationonlyModel = new AllocationOnlyModel();
        $this->refundamountModel = new RefundAmountModel();
        $this->studentModel = new StudentModel();
        $this->userModel = new UserModel();
        $this->teacherModel = new TeacherModel();
        $this->gradesContractModel = new GradesContractModel();
        $this->goodsContractModel = new GoodsContractModel();
        $this->gradesdetailModel = new GradesDetailsModel();
        $this->goodsModel = new GoodsModel();
        $this->studentsubjectinfosclassModel = new StudentSubjectInfosClassModel();
    }
}
